<template>
	<view class="pages" :class="themeName">
		<view class="login">
			<image class="logo" :src="appConfig.logo" mode="heightFix"></image>
			<view class="acount-login" v-if="loginType != 3">
				<view class="input">
					<u-field label-width="0" v-model="account" :placeholder="$zhTran('请输入手机号')" :input-border="false" />
				</view>
				<view class="input">
					<u-field v-if="loginType == 1" label-width="0" v-model="password" type="password"
						:password-icon="false" :placeholder="$zhTran('请输入密码')" :input-border="false">
						<view class="forget-btn p-l-20" slot="right">
							<router-link to="/bundle2/pages/forget_pwd/forget_pwd">{{$zhTran(' 忘记密码 ')}}</router-link>
						</view>
					</u-field>
					<u-field v-if="loginType == 2" label-width="0" v-model="code" :placeholder="$zhTran('请输入验证码')"
						:input-border="false">
						<view slot="right">
							<view class="sms-btn" @tap="sendSMS">
								<!-- 获取验证码 -->
								<u-verification-code unique-key="login" ref="uCode" @change="codeChange">
								</u-verification-code>
								<view class="xs">{{ codeTips }}</view>
							</view>
						</view>
					</u-field>
				</view>
				<button class="login-btn white br60" size="lg" @tap="loginFun">{{$zhTran('手机号快捷登录')}}</button>
				<view class="flex row-between">
					<view>
						<view class="lighter" v-if="hasLoginWay(1) && loginType == 2" @tap="changeLoginType">
							{{$zhTran('手机号密码登录')}}
						</view>
						<view class="lighter" v-if="hasLoginWay(2) && loginType == 1" @tap="changeLoginType">
							{{$zhTran('短信验证码登录')}}
						</view>
					</view>
					<router-link class="lighter" to="/bundle2/pages/register/register" v-if="isPhoneRegister">
						{{$zhTran('手机号快速注册')}}
					</router-link>
				</view>
			</view>
			<view class="other-login flex-col flex-1">
				<view class="flex-1 wx-login">
					<!-- #ifdef MP-WEIXIN -->
					<view v-if="isMnpWxAuth">
						<u-divider v-if="loginType != 3">{{$zhTran('其他登录方式')}}</u-divider>
						<view class="inline develop-line" @tap="mnpLogin">
							<view class="sm">{{$zhTran('一键手机号登录')}}</view>
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<view v-if="isOaWxAuth && isWeixin">
						<u-divider v-if="loginType != 3">{{$zhTran('其他登录方式')}}</u-divider>
						<view class="inline" @tap="getCodeUrl">
							<image class="image" :src="$getImageUri('resource/image/shopapi/default/icon_wechat.png')">
							</image>
							<view class="sm m-t-20">{{$zhTran('微信登录')}}</view>
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<view v-if="isAPPWxAuth">
						<u-divider v-if="loginType != 3">{{$zhTran('其他登录方式')}}</u-divider>
						<view class="inline" @tap="appLogin">
							<image class="image" :src="$getImageUri('resource/image/shopapi/default/icon_wechat.png')">
							</image>
							<view class="sm m-t-20">{{$zhTran('微信登录')}}</view>
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifdef MP-TOUTIAO -->
					<view v-if="isToutiaoAuth">
						<u-divider>{{$zhTran('其他登录方式')}}</u-divider>
						<view class="inline" @tap="ttLogin">
							<image class="image" :src="$getImageUri('resource/image/shopapi/uniapp/icon_toutiao.png')">
							</image>
							<view class="sm m-t-20">{{$zhTran('字节登录')}}</view>
						</view>
					</view>
					<!-- #endif  -->
				</view>

				<view class="m-b-40 sm flex row-center">
					<router-link to="/pages/index/index">
						<view class="sm p-20 br50" style="background: #acacac;color: #fff;">{{$zhTran('返回首页')}}</view>
					</router-link>
				</view>
				<view class="m-b-40 sm flex row-center">
					<u-checkbox v-model="explan_checked" name="explan" shape="circle">{{$zhTran('已阅读并同意')}}</u-checkbox>
					<router-link data-theme="" to="/bundle/pages/server_explan/server_explan?type=1">
						<view class="agreement">{{$zhTran('《服务协议》')}}</view>
					</router-link>
					{{$zhTran('和')}}
					<router-link to="/bundle/pages/server_explan/server_explan?type=2">
						<view class="agreement">{{$zhTran('《隐私协议》')}}</view>
					</router-link>
				</view>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<mplogin-popup v-model="showLoginPop" :logo="appConfig.logo" :title="appConfig.shop_name"
			:login-data="loginData" @close="closePopup" @update="handleSubmitInfo" />
		<!--  #endif -->

		<u-popup mode="center" length="86%" v-model="multiShow">
			<view class="multi-popup p-30">
				<view class="flex row-center font-size-40">{{$zhTran('选择用户')}}</view>
				<view class="multi-info m-t-20" v-for="item,idx in relevanceList" :key="idx">
					<view class="flex row-between p-20" @click="toLogin(idx,item)">
						<view class="avatar m-r-20">
							<u-image width="100rpx" height="100rpx" border-radius="10%" :src="item.user.avatar" />
						</view>
						<view class="info">
							<view class="name flex row-between">
								<text>{{item.user.nickname}}</text>
								<view class="flex">
									<view class="m-l-30 m-r-10">
										<u-image width="30rpx" height="30rpx" :src="$getImageUri(item.level_img)" />
									</view>
									<text>{{item.level}}</text>
								</view>
							</view>
							<view class="m-t-20 flex row-between">
								<text style="color: rgba(169, 169, 169, 1);">{{item.user.mobile}}</text>
								<view class="flex" v-if="item.is_used">
									<view class="circle"></view>
									<text>{{$zhTran('上次登录')}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapGetters
	} from "vuex";
	import {
		apiAuthLogin,
		apiAccountLogin,
		apiLoginCaptcha,
		apiToutiaoAuthLogin,
		apiAppWxLogin,
		apiUpdateUser,
	} from "@/api/app";
	import wechath5 from "@/utils/wechath5";
	import {
		isWeixinClient,
		currentPage,
		client,
		trottle
	} from "@/utils/tools";
	import Cache from "@/utils/cache";
	import {
		BACK_URL,
		INVITE_CODE,
		TOKEN,
	} from "@/config/cachekey";
	import {
		getCode,
		getUserProfile
	} from "@/utils/login";
	import {
		apiRelevanceList,
		apiLoginUser
	} from "@/api/user_multi_switch"
	import {
		apiLogout, //退出登录
	} from "@/api/user";
	const loginType = {
		ACCOUNT: 1,
		SMS_CODE: 2,
	};
	export default {
		data() {
			return {
				password: "",
				account: "",
				code: "",
				loginType: "",
				isWeixin: "",
				codeTips: "",
				showLoginPop: false,
				loginData: {},
				options: {},
				multiShow: false,
				relevanceList: [],
				explan_checked: false,
				// develop_flag: false
			};
		},

		methods: {
			...mapMutations(["login"]),
			...mapActions(["getUser"]),
			// 小程序微信登录
			async mnpLogin() {
				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}
				const {
					userInfo: {
						avatarUrl,
						nickName,
						gender
					},
				} = await getUserProfile();
				uni.showLoading({
					title: this.$zhTran("登录中..."),
					mask: true,
				});
				const wxCode = await getCode();
				const data = await apiAuthLogin({
					code: wxCode,
					nickname: nickName,
					headimgurl: avatarUrl,
				});
				if (data.is_new_user) {
					uni.hideLoading();
					this.showLoginPop = true;
					this.loginData = data;
				} else {
					this.loginHandle(data);
				}
				// this.loginHandle(data)
			},
			getCodeUrl() {
				wechath5.getWxUrl();
			},
			// 公众号微信登录
			async oaLogin(code) {
				if (!code) return;
				const data = await wechath5.authLogin(code);
				this.loginHandle(data);
			},
			oaAutoLogin() {
				// H5微信登录
				const {
					code
				} = this.$Route.query;
				this.isWeixin = isWeixinClient();
				if (this.isLogin) {
					// 已经登录 => 首页
					uni.switchTab({
						url: "/pages/index/index",
					});
					return;
				}
				if (code) {
					// 带有code => 登录
					return this.oaLogin(code);
				}
				if (this.isWeixin && this.isOaWxAutoLogin) {
					// 开启自动授权登录
					this.getCodeUrl();
				}
			},
			// app微信登录
			async appLogin() {
				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}
				uni.login({
					provider: "weixin",
					success: (res) => {
						uni.showLoading({
							title: this.$zhTran("登录中..."),
							mask: true,
						});
						const {
							openid,
							access_token
						} = res.authResult;
						apiAppWxLogin({
								openid,
								access_token,
							})
							.then((res) => {
								this.loginHandle(res);
							})
							.finally((res) => {
								uni.hideLoading();
							});
					},
				});
			},
			// 账号登录
			async loginFun() {
				const {
					account,
					password,
					telephone,
					code,
					loginType
				} = this;
				if (!account) {
					this.$toast({
						title: this.$zhTran("请输入手机号"),
					});
					return;
				}

				if (this.loginType == 1 && !password) {
					this.$toast({
						title: this.$zhTran("请输入密码"),
					});
					return;
				}
				if (this.loginType == 2 && !code) {
					this.$toast({
						title: this.$zhTran("请输入验证码"),
					});
					return;
				}

				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}

				apiAccountLogin({
					scene: loginType,
					account,
					password: loginType == 1 ? password : "",
					code: loginType == 2 ? code : "",
				}).then((res) => {
					this.loginHandle(res);
				});
			},
			// 登录结果处理
			async loginHandle(data) {

				await this.login(data);
				this.getUser();
				// 更新购物车
				this.$store.dispatch("getCartNum");
				uni.hideLoading();

				if (this.userInfo.user_multi_switch && !this.multiShow && this.relevanceList.length != 1) {
					apiRelevanceList()
						.then((res) => {
							this.relevanceList = res
							if (res.length == 1) {
								this.loginHandle(data);
							} else {
								this.multiShow = true
							}
						})
				} else {
					if (this.isBindMobile && !data.mobile) {
						return this.$Router.replace({
							path: "/bundle2/pages/bind_mobile/bind_mobile",
							query: {
								...this.options
							}

						});
					}
					this.goBack();
				}
			},
			toLogin(idx, row) {
				var idx_used = this.relevanceList.findIndex((item) => {
					return item.is_used == 1
				})
				apiLogout().then((res) => {
					apiLoginUser({
						user_id: row.user_id
					}).then((res) => {
						this.loginHandle(res);
					})
				});
			},
			goBack() {
				const {
					share_id,
					poster_type,
					poster_level,
					clsp_id
				} = this.options
				if (poster_type) {
					if (poster_type == 1) {
						this.$Router.push({
							path: '/bundle2/pages/community_group_purchase/leader/leader_center',
							query: {
								share_id
							}
						})
					} else {
						this.$Router.push({
							path: '/bundle2/pages/level_apply/apply',
							query: {
								share_id,
								poster_level
							}
						})
					}
				} else if (Cache.get('cloud_shop_enabled')) {
					this.$Router.push({
						path: `/bundle2/pages/cloud_shop/diyshop/index`,
						query: {
							clspId: clsp_id
						}

					})
				} else {
					if (getCurrentPages().length > 1) {
						// console.log(TOKEN + '000', Cache.get(TOKEN))
						this.$Router.back(1, {
							success: () => {
								const {
									onLoad,
									options
								} = currentPage();
								// 刷新上一个页面
								onLoad && onLoad(options);
							},
						});
					} else if (Cache.get(BACK_URL)) {
						this.$Router.replace(Cache.get(BACK_URL));
					} else {
						this.$Router.replaceAll("/pages/index/index");
					}
				}
				Cache.remove(BACK_URL);
			},
			changeLoginType() {
				if (this.loginType == loginType.ACCOUNT) {
					this.loginType = loginType.SMS_CODE;
				} else if (this.loginType == loginType.SMS_CODE) {
					this.loginType = loginType.ACCOUNT;
				}
			},
			// 发送验证码
			sendSMS() {
				if (!this.$refs.uCode.canGetCode) return;
				if (!this.account) {
					this.$toast({
						title: this.$zhTran("请输入手机号"),
					});
					return;
				}
				apiLoginCaptcha({
					mobile: this.account,
				}).then((res) => {
					this.$refs.uCode.start();
				});
			},

			codeChange(tip) {
				this.codeTips = tip;
			},
			// 头条小程序登录
			async ttLogin() {
				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}
				const code = await getCode();
				const [err, res] = await uni.getUserInfo();
				if (!res) {
					this.openSetting();
					return;
				}
				const {
					avatarUrl,
					nickName
				} = res.userInfo;
				uni.showLoading({
					title: this.$zhTran("登录中..."),
				});

				apiToutiaoAuthLogin({
						code,
						avatarUrl,
						nickName,
					})
					.then((res) => {
						this.loginHandle(res);
					})
					.catch((res) => {
						console.log(res);
						uni.hideLoading();
					});
			},
			openSetting() {
				uni.showModal({
					title: this.$zhTran("温馨提示"),
					content: this.$zhTran("您已拒绝授权，是否前往设置打开个人信息授权？"),
					confirmColor: this.themeColor,
					success(res) {
						if (res.confirm) {
							uni.openSetting();
						}
					},
				});
			},
			async handleSubmitInfo(e) {
				const loginData = this.loginData
				const res = await apiUpdateUser(e, loginData.token);
				this.loginHandle(loginData);
			},
			closePopup() {
				this.showLoginPop = false;
			},
		},
		computed: {
			// 开启手机号注册
			isPhoneRegister() {
				const {
					register_way
				} = this.appConfig;
				if (!register_way) {
					return false;
				}
				return register_way.some((item) => item == 1);
			},
			// 开启强制绑定手机号
			isBindMobile() {
				const {
					coerce_mobile
				} = this.appConfig;
				return coerce_mobile;
			},
			// 登录方式数组
			loginWay() {
				const {
					login_way
				} = this.appConfig;
				if (!login_way) return false;
				this.loginType = login_way[0] || "";
				return login_way;
			},
			// 是否包含对应的登录方式
			hasLoginWay() {
				return (type) => {
					return this.loginWay && this.loginWay.some((item) => item == type);
				};
			},
			// 开启小程序微信授权
			isMnpWxAuth() {
				const {
					mnp_wechat_auth
				} = this.appConfig;
				return mnp_wechat_auth;
			},

			// 开启小程序微信授权
			isOaWxAuth() {
				const {
					h5_wechat_auth
				} = this.appConfig;
				return h5_wechat_auth;
			},
			// 开启app微信授权
			isAPPWxAuth() {
				const {
					app_wechat_auth
				} = this.appConfig;
				return app_wechat_auth;
			},
			// 开启公众号微信自动登录
			isOaWxAutoLogin() {
				const {
					h5_auto_wechat_auth
				} = this.appConfig;
				return h5_auto_wechat_auth;
			},
			// 开启小程序头条登录
			isToutiaoAuth() {
				const {
					toutiao_auth
				} = this.appConfig;
				return toutiao_auth;
			},
		},
		onLoad() {

			// if (__wxConfig.envVersion === 'develop') {
			// 	this.develop_flag = true
			// }
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}

			this.options = this.$Route.query
			this.mnpLogin = trottle(this.mnpLogin);
			this.appLogin = trottle(this.appLogin);
			this.getCodeUrl = trottle(this.getCodeUrl);
			this.ttLogin = trottle(this.ttLogin);
			// #ifdef H5
			this.oaAutoLogin();
			// #endif
		},
		onUnload() {},
	};
</script>
<style lang="scss">
	page {
		background-color: #fff;

		padding: 0;
	}

	.login {
		height: 100vh;
		padding-top: 80rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;

		.logo {
			height: 126rpx;
			margin-bottom: 40rpx;
		}

		.acount-login,
		.other-login {
			width: calc(100% - 80rpx);

			.input {
				padding-top: 20rpx;
			}

			.login-btn {
				margin: 80rpx 0 50rpx;
				@include background_color();
			}

			.forget-btn {
				border-left: $-solid-border;
			}

			.sms-btn {
				text-align: center;
				border: 1px solid;
				width: 176rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 60rpx;
				@include font_color();
				@include border_color();
			}

			.wx-login {
				margin-top: 60rpx;

				.image {
					margin-top: 40rpx;
					width: 80rpx;
					height: 80rpx;
				}
			}

			.develop-line {
				color: #fff;
				background-color: #2ec840;
				padding: 20rpx 30rpx;
				margin-top: 20rpx;
				border-radius: 50rpx;
			}
		}

		.agreement {
			@include font_color;
		}
	}

	.multi-popup {

		width: 100%;
		background-color: #fff;
		border-radius: 10rpx;

		.multi-info {

			background-color: rgba(247, 249, 252, 1);
			position: relative;

			.info {
				width: calc(100% - 100rpx);
				color: rgba(56, 56, 56, 1);
				font-size: 24rpx;

				&>view {
					margin-bottom: 10rpx;
				}

				.name {
					font-size: 24rpx;
				}
			}

			.circle {
				background-color: rgba(169, 169, 169, 1);
				width: 15rpx;
				height: 15rpx;
				border-radius: 50%;
				margin-right: 10rpx;
			}

		}
	}
</style>